<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="text/javascript" src="js/react.development.js"></script>
    <script type="text/javascript" src="js/react-dom.development.js"></script>
    <script type="text/javascript" src="js/babel.min.js"></script>
    <script src="js/axios.min.js"></script>
</head>
<body>
    <div id="root">
    
    </div>
    <script type="text/babel">
        class Myform extends React.Component{
            constructor(props) {
                super(props);
                this.state = {
                    fileName:''
                };
                // 创建ref对象
                this.oneMyRef = React.createRef();
            }

            uploadFn=(e)=>{
                // e.persist();
                console.log(this.oneMyRef);
                let oneFile = this.oneMyRef.current.files[0];

                // 生成表单数据对象发送请求
                let oneFd = new FormData();
                oneFd.append('pic',oneFile);

                axios.post('https://game-cdn.moxigame.cn/resource/upload/img',oneFd).then(res=>{
                    console.log(res);
                    this.setState({
                        fileName:res.data.urls[0]
                    })
                })
            }

            showPic=()=>{
                if(this.state.fileName == '') {
                    return;
                }else {
                    // 这里的img标签快捷键输入会自动给src属性加双引号
                    // 需要注意的是这里的src属性加了大括号就不要在外面加双引号，否则不会解析变量，会作为字符串解析
                    return <img src={this.state.fileName} alt=""/>
                    // 总结：图片地址在浏览器url中可正常打开却无法作为src属性值的唯一可能就是没有解析为变量！！！
                }
            }

            render() {
                return (
                    <div>
                        <input type="file" ref={this.oneMyRef} name="上传图片" id=""/>   
                        <input type="button" onClick={this.uploadFn} value="上传"/><br/>
                        {this.showPic()}
                    </div>
                )
            }
        }
        ReactDOM.render(<Myform/>, document.getElementById('root'));
    </script>
</body>
</html>